package edu.cqie.smartfarm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.cqie.smartfarm.constant.CommonConstant;
import edu.cqie.smartfarm.constant.MessageConstant;
import edu.cqie.smartfarm.dto.FenceDTO;
import edu.cqie.smartfarm.dto.FenceQueryDTO;
import edu.cqie.smartfarm.dto.FenceUpdateDTO;
import edu.cqie.smartfarm.entity.Barn;
import edu.cqie.smartfarm.entity.Farm;
import edu.cqie.smartfarm.entity.Fence;
import edu.cqie.smartfarm.mapper.BarnMapper;
import edu.cqie.smartfarm.mapper.FarmMapper;
import edu.cqie.smartfarm.mapper.FenceMapper;
import edu.cqie.smartfarm.result.PageVO;
import edu.cqie.smartfarm.service.IFenceService;
import edu.cqie.smartfarm.utils.ThreadLocalUtil;
import edu.cqie.smartfarm.vo.FenceVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yyw
 * @since 2024-12-26
 */
@Service
@RequiredArgsConstructor
public class FenceServiceImpl extends ServiceImpl<FenceMapper, Fence> implements IFenceService {
    private final FenceMapper fenceMapper;
    private final FarmMapper farmMapper;
    private final BarnMapper barnMapper;
    /**
     * 获取围栏列表
     * @param fenceQueryDTO
     * @return
     */
    @Override
    public PageVO<FenceVO> getFenceList(FenceQueryDTO fenceQueryDTO) {
        Page<Fence> page = new Page<>(fenceQueryDTO.getPageNumber(), fenceQueryDTO.getPageSize());
        LambdaQueryWrapper<Fence> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(fenceQueryDTO.getFenceName()!=null, Fence::getFenceName, fenceQueryDTO.getFenceName())
                .like(fenceQueryDTO.getBarnName()!=null, Fence::getBarnName, fenceQueryDTO.getBarnName())
                .like(fenceQueryDTO.getFarmName()!=null, Fence::getFarmName, fenceQueryDTO.getFarmName())
                .eq(fenceQueryDTO.getStatus()!=null, Fence::getStatus, fenceQueryDTO.getStatus());
        Page<Fence> fencePage = page(page, queryWrapper);

        List<FenceVO> fenceVOList = BeanUtil.copyToList(fencePage.getRecords(), FenceVO.class);

        PageVO<FenceVO> pageVO = new PageVO<>();
        pageVO.setCurrent(fencePage.getCurrent());
        pageVO.setSize(fencePage.getSize());
        pageVO.setTotal(fencePage.getTotal());
        pageVO.setPages(fencePage.getPages());
        pageVO.setRecords(fenceVOList);
        return pageVO;
    }

    /**
     * 添加围栏
     * @param fenceDTO
     */
    @Override
    public void addFence(FenceDTO fenceDTO) {
        // 判断围栏是否存在
        LambdaQueryWrapper<Fence> queryWrapper = new LambdaQueryWrapper<Fence>()
                .eq(Fence::getFarmId, fenceDTO.getFarmId())
                .eq(Fence::getBarnId, fenceDTO.getBarnId())
                .eq(Fence::getFenceName, fenceDTO.getFenceName());
        if (count(queryWrapper) > 0) {
            throw new RuntimeException(MessageConstant.FENCE_EXISTS);
        }
        Fence fence = BeanUtil.copyProperties(fenceDTO, Fence.class);

        // 查询牧场和圈舍名称
        Farm farm = farmMapper.selectById(fenceDTO.getFarmId());
        if (farm == null){
            throw new RuntimeException(MessageConstant.FARM_NOT_EXISTS);
        }
        Barn barn = barnMapper.selectById(fenceDTO.getBarnId());
        if (barn == null){
            throw new RuntimeException(MessageConstant.BARN_NOT_EXISTS);
        }
        // 设置冗余字段
        fence.setFarmName(farm.getFarmName());
        fence.setBarnName(barn.getBarnName());
        // 获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        fence.setUserId((Integer) map.get(CommonConstant.USER_ID));

        save(fence);
    }

    /**
     * 修改围栏
     * @param fenceUpdateDTO
     */
    @Override
    public void updateFence(FenceUpdateDTO fenceUpdateDTO) {
        // 判断围栏是否存在
        Fence fence = getById(fenceUpdateDTO.getFenceId());
        if (fence == null) {
            throw new RuntimeException(MessageConstant.FENCE_NOT_EXISTS);
        }
        Barn barn = new Barn();
        if (fenceUpdateDTO.getBarnId() != null){
            barn = barnMapper.selectById(fenceUpdateDTO.getBarnId());
            if (barn == null){
                throw new RuntimeException(MessageConstant.BARN_NOT_EXISTS);
            }
        }
        // 判断围栏是否重复
        LambdaQueryWrapper<Fence> queryWrapper = new LambdaQueryWrapper<Fence>()
                .eq(Fence::getBarnId, fence.getBarnId())
                .eq(Fence::getFenceName, fenceUpdateDTO.getFenceName());
        if (count(queryWrapper) > 0) {
            throw new RuntimeException(MessageConstant.FENCE_EXISTS);
        }

        LambdaUpdateWrapper<Fence> updateWrapper = new LambdaUpdateWrapper<Fence>()
                .eq(Fence::getId, fenceUpdateDTO.getFenceId())
                .set(fenceUpdateDTO.getBarnId() != null, Fence::getBarnId, fenceUpdateDTO.getBarnId())
                .set(fenceUpdateDTO.getBarnId() != null, Fence::getBarnName, barn.getBarnName())
                .set(fenceUpdateDTO.getFenceName() != null && fenceUpdateDTO.getFenceName().length() > 0, Fence::getFenceName, fenceUpdateDTO.getFenceName())
                .set(fenceUpdateDTO.getStatus() != null, Fence::getStatus, fenceUpdateDTO.getStatus());
        fenceMapper.update(updateWrapper);
    }
}
